package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone) {
        //先判断手机号是否正确
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
        //进行验证码发送
        String code = RandomUtil.randomString(5);
        log.info("生成的验证码为{}",code);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2.校验验证码
        String code = loginForm.getCode();
        String cacheCode = redisTemplate.opsForValue().get(loginForm.getPhone());
        if (cacheCode == null || !cacheCode.equals(cacheCode)){
            return Result.fail("验证码错误！");
        }
        //3.一致 根据手机号查询用户
        User user = lambdaQuery().eq(User::getPhone, phone).one();
        //4.查询数据库是否有此用户
        if (ObjectUtil.isEmpty(user)){
            //如果没有 进行创建
            user = createLoginUser(phone);
        }
        //5.如果有此用户存入redis
        //生成token
        String token = UUID.randomUUID(true).toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将userDto 转换成map
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<String, Object>()
                ,CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((key,value)->{
                    return value.toString();
                }));

        String key = RedisConstants.LOGIN_USER_KEY + token;
        redisTemplate.opsForHash().putAll(key,map);
        //设置过期时间
        redisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL,TimeUnit.SECONDS);
        return Result.ok(token);
    }

    @Override
    public Result logout(HttpServletRequest request) {
        UserHolder.removeUser();
        if (request.getHeader("authorization") != null){
            redisTemplate.delete(RedisConstants.LOGIN_USER_KEY + request.getHeader("authorization"));
        }
        return Result.ok();
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        String key = RedisConstants.USER_SIGN_KEY +userId + keySuffix;
        //获取今天是本月的第几天
        int datOfMonth = now.getDayOfMonth();
        redisTemplate.opsForValue().setBit(key,datOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前登陆用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        String key = RedisConstants.USER_SIGN_KEY +userId + keySuffix;
        //获取今天是本月的第几天
        int datOfMonth = now.getDayOfMonth();
        // 5.获取本月截止今天为止的所有的签到记录，
        // 返回的是一个十进制的数字 BITFIELD sign:5:202203 GET u14 0
        List<Long> result = redisTemplate.opsForValue()
                .bitField(key, BitFieldSubCommands
                        .create().get(BitFieldSubCommands
                                .BitFieldType.unsigned(datOfMonth)).valueAt(0));
        //没有任何签到结果
        if (result == null || result.isEmpty()){
            return Result.ok();
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        while(true){
            //让这个数字与1 做与运算 得到数字的最后一个bit 判断这个bit是否为0
            if ((num & 1) == 0){
                //说明未签到 结束
                break;
            }else {
                //如果不为零 说明已签到 计数器+1
                count ++;
            }
            //把数字右移，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }

    private User createLoginUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
